<!-- views/student/CourseSelection.vue -->
<template>
  <div>
    <h2>可选课程列表</h2>
    <el-input v-model="searchKeyword" placeholder="搜索课程"></el-input>
    <div class="course-list">
      <el-card v-for="course in filteredCourses" :key="course.id">
        <h3>{{ course.name }}</h3>
        <p>学分: {{ course.credit }}</p>
        <p>剩余容量: {{ course.capacity }}</p>
        <el-button @click="handleEnroll(course.id)">选课</el-button>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { getCourses, enrollCourse } from '@/services/course';

const courses = ref([]);
const searchKeyword = ref('');

// 获取课程列表
const loadCourses = async () => {
  try {
    const res = await getCourses();
    courses.value = res.data;
  } catch (err) {
    ElMessage.error('加载课程失败');
  }
};

// 选课操作
const handleEnroll = async (courseId) => {
  try {
    await enrollCourse(courseId);
    ElMessage.success('选课成功');
    loadCourses(); // 刷新列表
  } catch (err) {
    ElMessage.error(err.message || '选课失败');
  }
};

// 计算属性过滤课程
const filteredCourses = computed(() => {
  return courses.value.filter(course => 
    course.name.includes(searchKeyword.value)
  );
});

loadCourses(); // 初始化加载
</script>